const express = require('express')
const { zzshequModel } = require('../model/models')
const router = express.Router()
function getDistance(lat1, lon1, lat2, lon2) {
    const R = 6371; // 地球半径，单位为千米
    const dLat = (lat2 - lat1) * (Math.PI / 180);
    const dLon = (lon2 - lon1) * (Math.PI / 180);
    const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c;
}
//附近功能
router.post('/nearby_people', async (req, res) => {
    const { latitude, longitude } = req.body;
    console.log(latitude, longitude);
    try {
        let data = await zzshequModel.find();
        const nearby = data.filter((user) => {
            const distance = getDistance(latitude, longitude, user.latitude, user.longitude);
            return distance < 1000; // 距离判断，单位可根据实际调整
        });
        res.json({
            data: nearby
        });
    } catch (error) {
        console.log('查询数据出错:', error);
        res.status(500).json({ error: '内部服务器错误，请稍后再试' });
    }
});
//获取用户数据
router.get("/ms_getlists", async (req, res) => {
    let { age, sex, suozaidi, xingzuo, xueli } = req.query
    let obj = {}
    if (age) {
        obj.age = { $lt: age }
    }
    if (sex) {
        if (sex == '不限') {
            return
        } else {
            obj.sex = sex
        }
    }
    if (suozaidi) {
        obj.suozaidi = suozaidi
    }
    if (xingzuo) {
        obj.xingzuo = xingzuo
    }
    if (xueli) {
        obj.xueli = xueli
    }
    let data = await zzshequModel.find({ $and: [obj] })
    res.send({
        code: 200,
        data
    })
})
//是否喜欢
router.get("/changelike", async (req, res) => {
    let { id, islike } = req.query
    console.log(id, islike);
    await zzshequModel.updateOne({ _id: id }, { islike: islike })
    res.send({
        code: 200
    })
})

module.exports = router